<template>
  <div>
    <div class="container">
      <el-row :gutter="50">
        <el-col :span="5">
          <div class="hd">
            <h4 class="title">部门列表</h4>
          </div>
          <TreeData
              :data="departmentList"
              :props="defaultProps"
              :defaultExpandAll="false"
              isSlot
              @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <div class="menu-item">
                <div class="label">{{ node.label }}</div>
              </div>
            </template>
          </TreeData>
        </el-col>
        <el-col :span="19">
          <el-form ref="query" :model="query" :inline="true" size="mini">
            <el-form-item label="状态：" prop="status">
              <el-select
                  v-model="query.status"
                  placeholder="请填写状态"
                  clearable
                  filterable
              >
                <el-option
                    v-for="item in $enum.getMapItems('status')"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="名称：" prop="name">
              <el-input
                  v-model="query.name"
                  placeholder="请填写名称"
                  clearable
              ></el-input>
            </el-form-item>

            <el-button
                size="mini"
                type="primary"
                icon="el-icon-search"
                @click="handleSearch"
            >搜索
            </el-button>
            <el-button
                size="mini"
                type="primary"
                icon="el-icon-delete"
                @click="handleClear"
            >清空
            </el-button>
          </el-form>

          <div class="handle-box">
            <el-button
                size="mini"
                type="primary"
                icon="el-icon-plus"
                class="handle-del mr10"
                @click="handleEdit()"
                v-if="$perm.hasPerm('button_position_add')"
            >添加
            </el-button>
            <el-button
                size="mini"
                type="primary"
                icon="el-icon-delete"
                class="handle-del mr10"
                @click="delAllSelection()"
                v-if="$perm.hasPerm('button_position_batchDelete')"
            >批量删除
            </el-button
            >
          </div>

          <el-table
              :data="records"
              border
              class="table"
              ref="multipleTable"
              header-cell-class-name="table-header"
              @selection-change="handleSelectionChange"
          >
            <el-table-column
                type="selection"
                width="55"
                align="center"
            ></el-table-column>
            <el-table-column prop="name" label="名称"></el-table-column>
            <el-table-column prop="code" label="编码"></el-table-column>
            <el-table-column label="状态" align="center">
              <template #default="scope">
                <el-tag
                    :type="
                scope.row.status === 'ENABLE'
                  ? 'success'
                  : scope.row.status === 'DISABLE'
                  ? 'danger'
                  : 'info'
              "
                >{{ $enum.getMapValue("status", scope.row.status).name }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createdTime" label="创建时间"></el-table-column>
            <el-table-column prop="modifiedTime" label="更新时间"></el-table-column>
            <el-table-column label="操作" width="180" align="center">
              <template #default="scope">
                <el-button
                    type="text"
                    icon="el-icon-edit"
                    @click="handleEdit(scope.row.id)"
                    v-if="$perm.hasPerm('button_position_edit')"
                >编辑
                </el-button>

                <el-button
                    type="text"
                    icon="el-icon-edit"
                    @click="handleEditStatus(scope.row.id, scope.row.status)"
                    v-if="$perm.hasPerm('button_position_editStatus')"
                >
                  {{ scope.row.status == "ENABLE" ? "禁用" : "启用" }}
                </el-button>
                <el-button
                    type="text"
                    icon="el-icon-delete"
                    class="red"
                    @click="handleDelete(scope.$index, scope.row)"
                    v-if="$perm.hasPerm('button_position_batchDelete')"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <custom-page
                :current="query.current"
                :size="query.size"
                :total="total"
                @current-change="handlePageChange"
            />
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 弹出框 -->
    <el-dialog
        :title="form.id ? '编辑' : '添加'"
        v-model="editVisible"
        width="50%"
        @closed="closed"
        @keyup.enter="saveEdit()"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-input v-if="visible" v-model="form.id"/>
        <el-input v-if="visible" v-model="form.departmentId"/>
        <el-form-item label="名称" prop="name">
          <el-input
              v-model="form.name"
              placeholder="请填写名称"
              clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="所属角色" prop="roleIds">
          <el-select
              v-model="form.roleIds"
              placeholder="请填写所属角色"
              class="handle-select mr10"
              clearable
              filterable
              multiple
          >
            <el-option
                v-for="item in form.roleList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
              size="small"
              v-model="form.remark"
              placeholder="请填写备注"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4 }"
              show-word-limit
              maxlength="99"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveEdit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>

import TreeData from "@/components/common/TreeData";
import {deepCopy, createObjectBase} from "@/utils";

import {departmentListEnabledByOrgIdApi} from "../../../api/mgt/power/department";

import {
  positionPageApi,
  positionEditStatusApi,
  positionRemoveApi, positionDetailExtendApi, positionEditApi, positionSaveApi,
} from "../../../api/mgt/power/position";
import {roleListByPositionIdApi} from "../../../api/mgt/power/role";

const obj = {
  //信息
  id: "",
  name: "",
  remark: "",
  departmentId: null,
  roleIds: [],
};

export default {
  components: {
    TreeData,
  },
  data() {
    return {
      defaultProps: {
        children: "children",
        label: "name",
      },
      query: {
        current: 1,
        size: 10,
        departmentId: null,
        status: null,
        name: null,
        code: null,
      },
      form: deepCopy(obj),
      visible: false,
      editVisible: false,
      departmentList: [],
      records: [],
      multipleSelection: [],
      delList: [],
      roleIds: [],
      total: 0,
      rules: {
        name: [
          {required: true, message: "请填写名称", trigger: "change"},
          {max: 20, message: "长度不能超过20个字符", trigger: "change"},
        ],
        departmentId: [
          {required: true, message: "请填写所属部门", trigger: "change"},
        ],
        roleIds: [
          {required: true, message: "请填写所属角色", trigger: "change"},
        ],
        remark: [
          {max: 99, message: "长度不能超过99个字符", trigger: "change"},
        ],
      },
    };
  },
  created() {
    this.getDepartmentList();
  },
  methods: {
    getDepartmentList() {
      departmentListEnabledByOrgIdApi().then((res) => {
        this.departmentList = res?.bizData;
        this.query.departmentId = res?.bizData[0].id;
        this.getData();
      });
    },
    handleNodeClick(data) {
      this.query.departmentId = data.id;
      this.getData();
    },
    // 获取数据
    getData() {
      positionPageApi(this.query).then((res) => {
        this.records = res?.bizData?.records;
        this.total = res?.bizData?.total;
      });
    },
    // 触发搜索按钮
    handleSearch() {
      this.query.current = 1;
      this.getData();
    },
    // 清空
    handleClear() {
      if (this.$refs.query != undefined) {
        this.$refs.query.resetFields();
        this.getData();
      }
    },
    // 删除操作
    handleDelete(index, row) {
      // 二次确认删除
      this.$confirm("确定要删除吗？", "提示", {
        type: "warning",
      }).then(() => {
        positionRemoveApi({ids: row.id}).then((res) => {
          this.getData();
        });
      });
    },
    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    delAllSelection() {
      const length = this.multipleSelection.length;
      if (length < 1) {
        this.$message.error("请选择数据");
        return;
      }
      this.multipleSelection.filter((item) => {
        this.delList.push(item.id);
      });
      const ids = this.delList.join(",");
      this.$confirm("确定要删除吗？", "提示", {
        type: "warning",
      }).then(() => {
        positionRemoveApi({ids: ids}).then((res) => {
          this.getData();
        });
      });
    },
    // 编辑操作
    handleEdit(id) {
      if (!id) {
        if (this.$refs.form != undefined) {
          this.$refs["form"].resetFields();
        }
        this.form.departmentId = this.query.departmentId;
        roleListByPositionIdApi({positionId: id}).then((res) => {
          this.form.roleList = res?.bizData;
        });
      } else {
        Promise.all([
          positionDetailExtendApi({id}),
          roleListByPositionIdApi({positionId: id}),
        ]).then(([positionDetail, roleList]) => {
          const formData = Object.assign(deepCopy(positionDetail?.bizData), {
            roleList: roleList?.bizData,
            roleIds: [],
          });
          if (formData.roleList !== null) {
            formData.roleIds = formData.roleList
                .filter((item) => item.checked)
                .map((item) => item.id);
          }
          this.form = formData;
        });
      }
      this.editVisible = true;
    },
    saveEdit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const data = createObjectBase(this.form, Object.keys(obj));
          const {id} = data;
          const fn = id ? positionEditApi : positionSaveApi;
          fn(data).then((res) => {
            this.editVisible = false;
            this.getData();
          });
        } else {
          return false;
        }
      });
    },
    closed() {
      this.idx = -1;
      this.form = deepCopy(obj);
    },
    // 启/禁用
    handleEditStatus(id, status) {
      let tip;
      let statusVal;
      if (status == "ENABLE") {
        tip = "确定要禁用吗？";
        statusVal = "DISABLE";
      } else if (status == "DISABLE") {
        tip = "确定要启用吗？";
        statusVal = "ENABLE";
      }
      this.$confirm(tip, "提示", {
        type: "warning",
      }).then(() => {
        positionEditStatusApi({id: id, status: statusVal}).then((res) => {
          this.getData();
        });
      });
    },
    // 分页导航
    handlePageChange(val) {
      this.query.current = val;
      this.getData();
    },
  },
};
</script>

<style scoped>
.hd {
  display: flex;
  padding-bottom: 10px;
  margin-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.title {
  flex: 1;
  color: #464646;
  font-size: 24px;
  font-weight: bold;
}

.menu-item {
  display: flex;
  flex: 1;
}

.menu-item .label {
  color: #666;
  font-size: 14px;
  flex: 1;
}

.menu-item .operate {
  color: #409eff;
  font-size: 14px;
}

.menu-item .operate span[type="danger"] {
  color: #f56c6c;
}

.menu-item:hover .operate {
  vertical-align: unset;
  opacity: 1;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
